<template>
    <div class="border-right" :style="{width:width+'px',height:'100%'}">
        <a-row class="file-browse-head border-bottom">
            <a-col :span="24">
                <div v-show="!collapsed" class="pull-right" style="display: inline;margin-right:40px;">
                    <a-button icon="file-add" style="border: 0px;" @click="addFileShow">笔记</a-button>
                    <a-button icon="file-add" style="border: 0px;">日记</a-button>
                </div>
                <a-icon
                        class="collapsed"
                        :type="collapsed ? 'menu-unfold' : 'menu-fold'"
                        @click="switchCollapsed"
                />
            </a-col>
        </a-row>
        <a-row class="file-browse" v-show="!collapsed">
            <a-col :span="14" class="border-right">
                <a-directory-tree
                        class="folder-tree"
                        :tree-data="folderTree"
                        :replace-fields="folderTreeReplaceFields"
                        :expandedKeys="folderExpandedKeys"
                        :selectedKeys="folderSelectedKeys"
                        expandAction="dblclick"
                        @select="onFolderSelect"
                        @expand="onFolderExpand"
                        @rightClick="onFolderRightClick"
                ></a-directory-tree>
            </a-col>
            <a-col :span="10">
                <a-directory-tree
                        class="file-list"
                        :tree-data="fileList"
                        :replace-fields="fileListReplaceFields"
                        :selectedKeys="fileSelectedKeys"
                        @select="onFileSelect"
                        @rightClick="onFileRightClick"
                ></a-directory-tree>
            </a-col>
        </a-row>
        <div>
            <a-menu class="right-menu"
                    :style="folderRightMenuStyle"
                    @mouseleave="onMouseLeave"
                    @click="onFolderRightMenuClick"
                    v-if="folderRightMenuVisible">
                <a-menu-item key="add-sub-folder">添加子目录</a-menu-item>
                <a-menu-item v-show="folderRightSelectedKey!=noteRootPath" key="add-bro-folder">添加同级目录</a-menu-item>
                <a-menu-item v-show="folderRightSelectedKey!=noteRootPath" key="change-name">改名</a-menu-item>
                <a-menu-item key="add-note" @click="addFileShow">添加笔记</a-menu-item>
                <a-menu-item v-show="folderRightSelectedKey!=noteRootPath" key="remove">删除</a-menu-item>
                <a-menu-item key="explorer">定位</a-menu-item>
                <a-menu-item key="refresh">刷新</a-menu-item>

            </a-menu>
            <a-menu class="right-menu"
                    :style="fileRightMenuStyle"
                    @mouseleave="onMouseLeave"
                    @click="onFileRightMenuClick"
                    v-if="fileRightMenuVisible">
                <a-menu-item key="change-name" @click="editFileShow(fileRightSelectedKey)">改名</a-menu-item>
                <a-menu-item key="remove">删除</a-menu-item>
                <a-menu-item key="explorer">定位</a-menu-item>
                <a-menu-item key="refresh">刷新</a-menu-item>
            </a-menu>
        </div>
        <div class="models">
            <!--添加文件-->
            <a-modal
                    :title="fileIsAdd?'添加文件':'修改文件名称'"
                    :visible="fileModelVisible"
                    @ok="fileModelHandleOk"
                    @cancel="()=>{fileModelVisible=false}"
                    cancelText="取消"
                    okText="确认"
            >
                <a-input
                        v-model="fileModelName"
                        :maxLength="100"
                        addonBefore="文件名称"
                ></a-input>
            </a-modal>
        </div>
    </div>
</template>

<script>
    import fs from 'fs'
    import path from 'path'
    import {getProperty, setProperty} from '../utils/config'
    import ACol from "ant-design-vue/es/grid/Col";
    import AButton from "ant-design-vue/es/button/button";
    import {openExplorer, removeSync, addFileSync, getFileName} from '../utils/fileUtil'

    export default {
        components: {
            AButton,
            ACol
        },
        props: {
            extendWidth: {
                type: Number,
                default: 300,
            },
            collapsedWidth: {
                type: Number,
                default: 30,
            },

        },
        data() {
            return {
                _extendWidth: 0,
                _collapsedWidth: 30,
                width: 0,
                collapsed: false,
                folderExpandedKeys: [],
                folderSelectedKeys: [],
                fileSelectedKeys: [],
                folderTree: [],
                fileList: [],
                noteRootPath: '',
                //添加文件扩展名
                newFileExt: '.md',
                folderTreeReplaceFields: {
                    title: 'folderName',
                    key: 'folderPath'
                },
                fileListReplaceFields: {
                    title: 'fileName',
                    key: 'filePath'
                },
                folderRightMenuStyle: {
                    top: '0px',
                    left: '0px'
                },
                fileRightSelectedKey: "",
                folderRightMenuVisible: false,
                fileRightMenuStyle: {
                    top: '0px',
                    left: '0px'
                },
                fileRightSelectedKey: "",
                fileRightMenuVisible: false,
                fileModelVisible: false,
                fileModelName: '',
                fileIsAdd: true,
            };
        },
        methods: {
            switchCollapsed() {
                this.collapsed = !this.collapsed
                if (this.collapsed)
                    this.width = this._collapsedWidth
                else
                    this.width = this._extendWidth
                this.$emit('collapse', this.width)
            },
            expand() {
                if (this.collapsed) {
                    this.switchCollapsed()
                }
            },
            collapse() {
                if (!this.collapsed) {
                    this.switchCollapsed()
                }
            },
            onFolderExpand(expandedKeys) {
                this.folderExpandedKeys = expandedKeys

            },
            onFolderSelect(selectedKeys) {
                console.log(selectedKeys)
                if (this.folderSelectedKeys.length == 0 || selectedKeys[0] != this.folderSelectedKeys[0]) {
                    this.folderSelectedKeys = selectedKeys
                    this.loadFileList(this.folderSelectedKeys[0])
                }
            },
            onFileSelect(selectedKeys) {
                this.fileSelectedKeys = selectedKeys
                if (selectedKeys.length > 0)
                    this.$emit('fileSelect', selectedKeys[0])
                else
                    this.$emit('fileSelect', '')

            },
            onFolderRightClick(e) {
                this.onFolderSelect([e.node.eventKey])
                this.folderRightSelectedKey = e.node.eventKey
                this.folderRightMenuVisible = true;
                this.folderRightMenuStyle.top = e.event.clientY - 10 + "px";
                this.folderRightMenuStyle.left = e.event.clientX - 60 + "px";
                document.body.addEventListener("click", this.bodyClick);
            },
            onFileRightClick(e) {
                e.event.stopPropagation()
                this.fileRightSelectedKey = e.node.eventKey
                this.fileRightMenuVisible = true;
                this.fileRightMenuStyle.top = e.event.clientY - 20 + "px";
                this.fileRightMenuStyle.left = e.event.clientX - 70 + "px";
                document.body.addEventListener("click", this.bodyClick);
            },
            traverseFolder(basePath) {
                var folders = [];
                //读取当前文件夹
                let items = fs.readdirSync(basePath)
                items.map(item => {
                    let p = path.join(basePath, item)
                    let stat = fs.statSync(p)
                    if (stat.isDirectory()) {
                        let children = this.traverseFolder(p)
                        folders.push({
                            //文件夹名称
                            folderName: item,
                            //文件夹路径
                            folderPath: p,
                            //上次访问时间
                            folderAtime: stat.atime,
                            //上次修改时间
                            folderMtime: stat.mtime,
                            //创建时间
                            folderBirthtime: stat.birthtime,
                            children: children
                        })
                    }
                })
                return folders
            },
            loadFolderTree(rootPath) {
                let children = this.traverseFolder(rootPath)
                this.folderTree = [{
                    folderName: "笔记本",
                    folderPath: rootPath,
                    children: children
                }]
            },
            reloadFolderTree() {
                if (!this.noteRootPath)
                    this.$message.info("根目录不存在")
                else
                    this.loadFolderTree(this.noteRootPath)
            },
            loadFileList(basePath) {
                let _this = this
                this.fileList = [];
                let list = []

                fs.readdir(basePath, (err, files) => {
                    files.map(file => {
                        let p = path.join(basePath, file)
                        let stat = fs.statSync(p)
                        if (stat.isFile()) {
                            list.push({
                                //文件夹名称
                                fileName: file,
                                //文件路径
                                filePath: p,
                                //上次访问时间
                                fileAtime: stat.atime,
                                //上次修改时间
                                fileMtime: stat.mtime,
                                //创建时间
                                fileBirthtime: stat.birthtime,
                            })
                        }
                    })
                    /*按创建日期排序*/
                    _this.fileList = list.sort((a, b) => {
                        return a.fileBirthtime > b.fileBirthtime
                    })

                    if (_this.fileSelectedKeys.length == 0)
                        _this.onFileSelect([])

                    let item = _this.fileList.find(file => {
                        return file.filePath == _this.fileSelectedKeys[0]
                    })
                    if (!item)
                        _this.onFileSelect([])
                    else
                        _this.onFileSelect(_this.fileSelectedKeys)
                })
            },
            reloadFileList() {
                if (this.folderSelectedKeys.length > 0)
                    this.loadFileList(this.folderSelectedKeys[0])
                else
                    this.$message.info("请选择目录")
            },
            bodyClick() {
                this.folderRightMenuVisible = false;
                this.fileRightMenuVisible = false;

                document.body.removeEventListener("click", this.bodyClick);
            },
            onMouseLeave() {
                this.folderRightMenuVisible = false;
                this.fileRightMenuVisible = false;
            },
            /**
             * 文件夹列表右键菜单点击事件
             * @param option
             */
            onFolderRightMenuClick(option) {
                switch (option.key) {
                    case "add-sub-folder":
                        break
                    case "add-bro-folder":
                        break
                    case "change-name":
                        break
                    case "add-note":
                        break
                    case "remove":
                        if (this.folderRightSelectedKey == this.noteRootPath) {
                            return _this.$message.warn("根目录禁止删除")
                        }
                        try {
                            removeSync(this.folderRightSelectedKey)
                            this.reloadFolderTree()
                        }
                        catch (err) {
                            return _this.$message.error("删除失败")
                        }
                        break
                    case "explorer":
                        openExplorer(this.folderRightSelectedKey)
                        break
                    case "refresh":
                        this.reloadFolderTree()
                        break
                    default:
                        break
                }
            },
            /**
             * 文件列表右键菜单点击事件
             * @param option
             */
            onFileRightMenuClick(option) {
                switch (option.key) {
                    case "change-name":
                        break
                    case "remove":
                        try {
                            removeSync(this.fileRightSelectedKey)
                            this.reloadFileList()
                        }
                        catch (err) {
                            return _this.$message.error("删除失败")
                        }
                        break
                    case "explorer":
                        openExplorer(this.fileRightSelectedKey)
                        break
                    case "refresh":
                        this.reloadFileList()
                    default:
                        break
                }
            },
            //添加文件，显示模态框
            addFileShow() {
                if (this.folderSelectedKeys.length == 0 || !this.folderSelectedKeys[0]) {
                    return this.$message.error("请先选择文件夹")
                }
                this.fileModelName = ""
                this.fileModelVisible = true
                this.fileIsAdd = true
            },
            //修改文件名，显示模态框
            editFileShow(fileName) {
                this.fileModelVisible = true
                this.fileIsAdd = false
                this.fileModelName = getFileName(fileName)
            },
            fileModelHandleOk() {
                if (this.folderSelectedKeys.length == 0 || !this.folderSelectedKeys[0]) {
                    return this.$message.error("请先选择文件夹")
                }

                var reg = new RegExp('[\\\\/:*?\"<>|]');
                if (!this.fileModelName && this.fileModelName != 0)
                    return this.$message.error("文件名不能为空")
                if (reg.test(this.fileModelName)) {
                    return this.$message.error("文件名格式有误，不允许包含/:*?\"<>|")
                }

                let fileName = this.folderSelectedKeys[0] + '\\' + this.fileModelName + this.newFileExt
                try {
                    addFileSync(fileName)
                    this.$message.success("文件添加成功")
                    this.fileModelVisible = false
                    this.fileSelectedKeys = [fileName]
                    this.reloadFileList()
                } catch (e) {
                    this.$message.error(e.message)
                }
                /*
                this.fileModelName;
                this.newFileExt*/
            }
        },
        mounted: function () {
            this._extendWidth = this.extendWidth;
            this._collapsedWidth = this.collapsedWidth
            this.width = this._extendWidth;
            this.collapse = false;

            this.noteRootPath = getProperty("noteRootPath")
            this.folderExpandedKeys.push(this.noteRootPath)

            this.loadFolderTree(this.noteRootPath)
        }
    }
</script>
<style scoped>
    .file-browse-head {
        height: 33px;
        background: white;
    }

    .file-browse {
        width: 100%;
        height: calc(100% - 33px);
        background: white;
    }

    .file-browse .ant-col {
        height: 100%;
        padding: 10px;
        overflow-y: auto;
    }

    .folder-tree /deep/ .ant-tree-iconEle,
    .file-list /deep/ .ant-tree-iconEle {
        display: none !important;
    }

    .folder-tree /deep/ .ant-tree-switcher {
        width: 8px;
    }

    .folder-tree /deep/ .ant-tree-child-tree {
        overflow: hidden;
    }

    .file-list /deep/ .ant-tree-switcher {
        display: none !important;
    }

    .file-list {
        overflow: hidden;
    }

    .collapsed {
        font-size: 20px;
        margin-top: 7px;
        right: 5px;
        position: absolute;
    }

    .right-menu {
        position: absolute;
        border: 1px solid #eee;
        z-index: 9999;
    }

    .right-menu /deep/ .ant-menu-item {
        height: 25px;
        line-height: 25px;
    }
</style>